import React from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { useDiaryStore } from '../../store/diaryStore';

const PopularTagsChart: React.FC = () => {
  const getPopularTags = useDiaryStore((state) => state.getPopularTags);
  const popularTags = getPopularTags();
  
  // Transform data for chart (limit to top 8 tags)
  const data = popularTags.slice(0, 8).map(tag => ({
    tag: tag.tag,
    count: tag.count
  }));

  if (data.length === 0) {
    return (
      <div className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-6">
        <h3 className="text-lg font-semibold text-warm-gray-800 mb-4">
          Popular Tags
        </h3>
        <div className="flex items-center justify-center h-64 text-warm-gray-500">
          <p>No tags available</p>
        </div>
      </div>
    );
  }

  const CustomTooltip = ({ active, payload, label }: any) => {
    if (active && payload && payload.length) {
      return (
        <div className="bg-white p-3 border border-warm-gray-200 rounded-lg shadow-lg">
          <p className="font-medium text-warm-gray-800">{label}</p>
          <p className="text-sm text-warm-gray-600">
            Used {payload[0].value} times
          </p>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-6">
      <h3 className="text-lg font-semibold text-warm-gray-800 mb-4">
        Popular Tags
      </h3>
      <ResponsiveContainer width="100%" height={300}>
        <BarChart data={data} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="#f3f4f6" />
          <XAxis 
            dataKey="tag" 
            stroke="#6b7280"
            fontSize={12}
            tickLine={false}
            angle={-45}
            textAnchor="end"
            height={80}
          />
          <YAxis 
            stroke="#6b7280"
            fontSize={12}
            tickLine={false}
            axisLine={false}
          />
          <Tooltip content={<CustomTooltip />} />
          <Bar 
            dataKey="count" 
            fill="#84cc16"
            radius={[4, 4, 0, 0]}
          />
        </BarChart>
      </ResponsiveContainer>
      <div className="mt-4 text-sm text-warm-gray-600">
        Showing top {data.length} most used tags
      </div>
    </div>
  );
};

export default PopularTagsChart;